package com.uetoken.cn.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.BindAccountBean;
import com.uetoken.cn.bean.MsgBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.manager.UEDataManager;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.view.DialogHelper;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * author : hejunming
 * e-mail : 925379434@qq.com
 * date   : 2018/10/10 18:16
 */
public class APPAuthorizationActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.line1)
    View line1;
    @BindView(R.id.ygLogoIv)
    ImageView ygLogoIv;
    @BindView(R.id.appLogoTv)
    TextView appLogoTv;
    @BindView(R.id.accountInfoTv)
    TextView accountInfoTv;
    @BindView(R.id.switchAccountTv)
    TextView switchAccountTv;
    @BindView(R.id.accountInfoLayout)
    RelativeLayout accountInfoLayout;
    @BindView(R.id.explainTitleTv)
    TextView explainTitleTv;
    @BindView(R.id.appAuthorizationBtn)
    Button appAuthorizationBtn;
    @BindView(R.id.authorizationLayout)
    LinearLayout authorizationLayout;
    /**
     * 绑定第三方账号请求码
     */
    private static final int REQUEST_NETWORK_BINDING = 10;

    private String name = "";
    private String mobile = "";
    private String accountInfo = "";
    private String nodeID = "";
    private String nodeCode = "";
    private String uriHost;
    private int actionType = 0;
    private String appname = "";
    private String uid;
    private HashMap<String, Integer> mPlatformMap;

    @Override
    public int getLayoutId() {
        return R.layout.activity_app_authorization;
    }

    @Override
    public void initView() {
        // 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarDarkMode(this);
        }
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        mPlatformMap = UEDataManager.getInstance().getOpensType();
        initTopBar();

    }

    @Override
    public void init() {

    }

    private void initTopBar() {
        mTopbar.setTitle(R.string.str_authorization_title);
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toBackAPP(true);
            }
        });
    }

    @OnClick({R.id.switchAccountTv, R.id.appAuthorizationBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.switchAccountTv:
                //清除用户配置信息
                SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).clear();
                Intent intentToLogin = new Intent(this, LoginActivity.class);
                intentToLogin.putExtra("isAuthorization", true);
                intentToLogin.putExtra("uriHost", uriHost);
                intentToLogin.putExtra("flag", "authorization");
                intentToLogin.putExtra("nodeCode", nodeCode + "");
                intentToLogin.putExtra("actionType", actionType + "");
                startActivity(intentToLogin);
                break;
            case R.id.appAuthorizationBtn:
                showDialogConfirm();
                break;
        }
    }

    private void showDialogConfirm() {
        DialogHelper.showMessageDialog(APPAuthorizationActivity.this, getResources().getString(R.string.str_warm_prompt),
                getResources().getString(R.string.str_authorization_dialog),
                getResources().getString(R.string.str_cancel),
                getResources().getString(R.string.str_confirm),
                new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        //取消
                        dialog.dismiss();
                    }
                }, new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        //确定
                        if (actionType == 6000) {
                            showLoading();
                            setBinding();
                        } else {
                            toBackAPP(false);
                        }
                    }
                });
    }

    /**
     * 绑定第三方账号
     */
    private void setBinding() {
        if ("yougu".equals(uriHost)) {
            appname = "YOUGU";
        } else if ("pcn".equals(uriHost)) {
            appname = "PCN";
        }
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getBindThirdpartyUrl(), REQUEST_NETWORK_BINDING,
                Params.getBindThirdpartyParams(nodeID, mPlatformMap.get(appname) + "", uid));
    }


    private void toBackAPP(boolean isBack) {
        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.SP_TRIRDPARTY_APP_REQUEST_AUTHORIZATION, "");
        String parameter = "&nodeCode=" + "";
        String url;
        if (actionType == 6000) {
            if (isBack) {
                parameter = "&nodeCode=" + "";
            } else {
                parameter = "&nodeCode=" + nodeCode;
            }
        } else {
            parameter = "&nodeCode=" + nodeCode;
        }
        url = uriHost + "://ue?actionType=" + actionType + parameter;
        LogUtils.dTag("toBackAPP==", "toBackAPP== url = " + url);
        Intent intent = new Intent();
        intent.setData(Uri.parse(url));
        startActivity(intent);
        finish();
    }

    @Override
    protected void onStart() {
        uriHost = getIntent().getStringExtra("uriHost");
        uid = getIntent().getStringExtra("nodeCode");
        String type = getIntent().getStringExtra("actionType");
        actionType = Integer.parseInt(type);

        name = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_NAME, "");
        mobile = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_MOBILE_NO, "");
        nodeID = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_ID, "");
        nodeCode = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getString(Constant.SP_NODE_CODE, "");
        accountInfo = (name.equals(mobile) ? mobile : name) + (TextUtils.isEmpty(nodeCode) ? "" : "(" + nodeCode + ")");
        if (accountInfo != null) {
            accountInfoTv.setText(accountInfo);
        }
        Drawable drawable = null;
        String appName = null;
        if (actionType == 6000) {
            drawable = getResources().getDrawable(R.drawable.yougu_logo_icon);
            appName = getResources().getString(R.string.str_yg);
        }
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            appLogoTv.setCompoundDrawables(null, drawable, null, null);
        }
        if (appName != null) {
            appLogoTv.setText(appName);
        }
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).put(Constant.SP_TRIRDPARTY_APP_REQUEST_AUTHORIZATION, "");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            toBackAPP(true);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("onSuccessResponse==", "onSuccessResponse== requestCode = " + requestCode + " response = " + response);
        dissmissDialog();
        if (requestCode == REQUEST_NETWORK_BINDING) {
            MsgBean bind_msgBean = new Gson().fromJson(response, MsgBean.class);
            if (bind_msgBean.getResult() > 0) {
                toBackAPP(false);
            }
            ToastUtils.showShort(bind_msgBean.getMessage());
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
//        toBackAPP(true);
        ToastUtils.showShort(e.getMessage());
    }
}
